package com.cesc.demo.repository;

import com.cesc.demo.mode.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Repository
public class ProductReactiveRedisRepositoryImpl {

    @Autowired
    private ReactiveRedisTemplate<String, Product> reactiveRedisTemplate;

    private static final String HASH_NAME="Product";

    public Mono<Boolean> saveProduct(Product product){
        return reactiveRedisTemplate.opsForValue().set(HASH_NAME+product.getId(),product);
    }

    public Mono<Boolean> updateProduct(Product product){
        return reactiveRedisTemplate.opsForValue().set(HASH_NAME+product.getId(),product);
    }

    public Mono<Boolean> deleteProduct(String  productId){
        return reactiveRedisTemplate.opsForValue().delete(HASH_NAME+productId);
    }

    public Mono<Product> findProductById(String productId){
        return  reactiveRedisTemplate.opsForValue().get(HASH_NAME+productId);
    }

    public Flux<Product> findAllProduct(){
        return  reactiveRedisTemplate.keys(HASH_NAME+"*")
                .flatMap((String key)->{
                    Mono<Product> mono=reactiveRedisTemplate.opsForValue().get(key);
                    return mono;
                });
    }
}
